package com.ys.tdm.util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.ys.code.generator.core.MyCodeGenerator;
import com.ys.tdm.bean.code.DbConectionCondition;

/**
 * JDBC数据库公共连接
* @Title:  
* @Description:TODO
* @author huanghongjing  
* @date 2018年3月8日 上午10:07:44 
* @version V1.0 
* @Copyright:Copyright (c) 亚厦股份2016 ~ 2017 版权所有
 */

@Service
public class Connectiondb {
	public static void main(String[] args) throws Exception {
		Connectiondb cg = new Connectiondb();
	}
    public static Connection connectDataBase(DbConectionCondition dbConectionCondition) {
        Connection conn = null;
        //加载驱动
        try {
            Class.forName(dbConectionCondition.getDriveClassName());
        } catch (ClassNotFoundException e) {
            System.out.println("load driver failed!");
            e.printStackTrace();
        }
        //连接数据库
        try {
            conn = DriverManager.getConnection(dbConectionCondition.getUrl(), dbConectionCondition.getUser(), dbConectionCondition.getPassword());
            System.out.println("connect success!");
        } catch (SQLException e) {
            System.out.println("connect failed!");
            e.printStackTrace();
        }
        return conn;
    }

	public ReturnVo<List<String>> getDataBase(DbConectionCondition dbConectionCondition) {
		Connection connectDataBase = Connectiondb.connectDataBase(dbConectionCondition);
		ReturnVo<List<String>> vo = new ReturnVo<>(0,"数据库连接失败！请使用正确的链接");
		List<String> dataBase = new ArrayList<>();
		if (connectDataBase!= null) {
			String sql = "SHOW DATABASES";
			try {
				PreparedStatement prepareStatement = connectDataBase.prepareStatement(sql);
				ResultSet rs = prepareStatement.executeQuery();
				while (rs.next()) {
					dataBase.add(rs.getString("DataBase"));
				}
				vo.setCode(1);
				vo.setData(dataBase);
				vo.setMsg("成功建立链接");
				connectDataBase.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return vo;
	}
}